#!/bin/sh
filesize='66427'
sha512='b9e8fdadef67f6efc8696f9dcd32f6766accdcbdf33184453553e318db8d46876208996ca480a93c66f3d2ff28fe9baf3e1bcc3ca77eb9baf687daeba484e2f5'
version=0.4.0

filename="$C"/butch-$version.tar.bz2

if [ -z "$BUTCH_BIN" ] ; then

tarxf http://ftp.barfooze.de/pub/butch/ butch-$version .tar.bz2 butch ||
tarxf http://foss.aueb.gr/mirrors/linux/butch/ butch-$version .tar.bz2 butch

getfilesize() {
	wc -c "$1" | cut -d " " -f 1
}

sz=$(getfilesize "$filename")

if [ "$sz" != "$filesize" ]; then
    printf -- "error: build-butch: wrong filesize. got: %d expected: %d\n" "$sz" "$filesize"
    exit 1
fi

if ! which sha512sum > /dev/null ; then
	echo "warning: sha512sum utility not found, disabling hash check"
	sha="$sha512"
	sleep 2
else
read sha _ <<EOF
$(sha512sum "$filename")
EOF
fi

if [ "$sha" != "$sha512" ]; then
    printf -- "error: build-butch: hash doesn't match.\n"
    exit 1
fi

# this speeds up compilation a bit
echo "CFLAGS=-O0" > butch/config.mak

# if on arm or mips, we only use one build thread to not exhaust memory
[ "$A" = "arm" ] || [ "$A" = "mips" ] && sed -i \
  's@#define NUM_BUILD_THREADS 2@#define NUM_BUILD_THREADS 1@' butch/butch.c

./build.sh
BUTCH_BIN=butch/butch

fi

cp "$BUTCH_BIN" "$R"/bin/butch-core

